package com.sky.module.security.handler;

import com.alibaba.fastjson.JSON;
import com.sky.module.security.exception.CustomerAuthenticationException;
import com.sky.module.system.loginlog.service.LoginLogService;
import com.sky.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/***
 * @description 登录认证失败处理器
 * @param
 * @return
 * @date 2023/2/20 10:04
 *
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Autowired
    private LoginLogService loginLogService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");

//        保存异常信息
        String message = null;
        int code = 500;

        final ServletOutputStream outputStream = response.getOutputStream();
        if (exception instanceof AccountExpiredException) {
            message = "账户过期，登录失败";

        } else if (exception instanceof BadCredentialsException) {
            message = "用户名或密码错误，登录失败";
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码过期，登录失败";
        } else if (exception instanceof DisabledException) {
            message = "账户过期，登录失败";
        } else if (exception instanceof LockedException) {
            message = "账户被锁定，登录失败";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            message = "账户不存在,登录失败";
        } else if (exception instanceof CustomerAuthenticationException) {
            // 校验token过程中抛出的异常
            message = exception.getMessage();
            code = 600;
        } else {
            message = "登录失败";
        }
        // 登录失败 记录登录失败日志信息
//        loginLogService.saveLoginLogInfoFail();
//        将结果转成json格式
        String result = JSON.toJSONString(Result.error().code(code).message(message));
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }
}
